package com.hjjt.baselib

import android.content.Context
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.sunstar.baselib.R
import kotlin.reflect.KClass

abstract class HJBaseActivity<T : ViewDataBinding> : FragmentActivity() {

    var appbarTitle: TextView? = null
    var appbarBackIcon: ImageView? = null
    val binding: T by lazy {
        DataBindingUtil.setContentView<T>(this, initLayoutId())
    }
    var mContext: FragmentActivity? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = this
        initBinding(binding)
        initTitle()
        binding.lifecycleOwner = this
    }

    /**
     * 设置databinding.
     *
     * @param binding 数据绑定
     */
    abstract fun initBinding(binding: T)

    fun <VM : ViewModel> registerViewModel(clazz: Class<VM>): VM =
        ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(clazz)

    private fun initTitle() {
        appbarTitle = findViewById(R.id.appbar_title)
        appbarBackIcon = findViewById(R.id.appbar_back_icon)
        appbarTitle?.run {
            text = setTitleText()
        }
        appbarBackIcon?.setOnClickListener {
            setBackOnClick()
        }
    }

    /**
     * 设置标题.
     *
     * @return 标题名称
     */
    abstract fun setTitleText(): CharSequence?

    private fun setBackOnClick() {
        onBackPressed()
    }

    /**
     * 设置页面资源名称
     *
     * @return 页面资源id
     */
    abstract fun initLayoutId(): Int
    override fun onDestroy() {
        super.onDestroy()
        mContext = null
    }
}
